package demo4;
class Money implements Cloneable{
    public double m = 12.5;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Person implements Cloneable{
    public int id;
    public Money money = new Money();

    @Override
    protected Object clone() throws CloneNotSupportedException {
        //return super.clone(); //这是浅拷贝
        Person tmp = (Person) super.clone();
        //由于浅拷贝后两个对象的money指向同一块位置，改变一个对象会把另一个对象也改变，所以我们把money单独拷贝一份
        tmp.money = (Money) this.money.clone();
        return tmp;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                '}';
    }
}
//要实现克隆步骤
//1，要实现接口Cloneable，   implements Cloneable{
//protected Object clone() throws CloneNotSupportedException{ return super.clone; }
//2，然后重写接口里的clone方法
//3,声明异常
public class Test2 {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person();

        Person person2 = (Person)person.clone();
        person2.money.m = 1999;

        System.out.println("person："+person.money.m);

        System.out.println("person2："+person2.money.m);
    }
}
